import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import ChatView from '../views/ChatView.vue'
import  {useUserStore} from '../stores/user.js'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'login',
            component: LoginView,
            meta: { requiresAuth: false }
        },
        {
            path: '/chat',
            name: 'chat',
            component: ChatView,
            meta: { requiresAuth: true }
        }
    ]
})

router.beforeEach((to, from, next) => {
    const userStore = useUserStore()
    const isAuthenticated = userStore.token

    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/')
    } else if (to.name === 'login' && isAuthenticated) {
        next('/chat')
    } else {
        next()
    }
})

export default router